//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { appWindow } from '@tauri-apps/api/window';
import style from './index.module.less';
import { Button, Layout, Progress, Segmented, Space, message } from 'antd';
import { observer } from 'mobx-react';
import { useStores } from '@/hooks';
import { EyeInvisibleFilled, InfoCircleOutlined, LogoutOutlined, MehFilled, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { checkUpdate } from '@tauri-apps/api/updater';
import { check_update } from '@/api/main';
import { ADMIN_PATH } from '@/utils/constant';
import { useLocation } from 'react-router-dom';
import QuickAccess from './QuickAccess';
import ServerConnInfo from './ServerConnInfo';
import UserPhoto from '../Portrait/UserPhoto';
import FeedBackModal from './FeedBackModal';
import AppNavigator from './AppNavigator';
import { open as shell_open } from '@tauri-apps/api/shell';
import { listen } from '@tauri-apps/api/event';
import type * as NoticeType from '@/api/notice_type';

const { Header } = Layout;

const MyHeader: React.FC<{ style?: React.CSSProperties; className?: string }> = ({
  ...props
}) => {
  const location = useLocation();

  const userStore = useStores('userStore');
  const appStore = useStores('appStore');

  const [hasNewVersion, setHasNewVersion] = useState(false);
  const [updateProgress, setUpdateProgress] = useState(0);

  const handleClick = async function handleClick(type: string) {
    switch (type) {
      case 'hide':
        await appWindow.hide();
        break;
      case 'exit':
        appStore.showExit = true;
        break;
      case 'minimize':
        await appWindow.minimize();
        break;
      case 'maximize':
        const isMaximized = await appWindow.isMaximized();
        if (isMaximized) {
          await appWindow.unmaximize();
        } else {
          await appWindow.maximize();
        }
        break;
    }
  };

  const checkNewVersion = async (showDialog: boolean) => {
    try {
      const res = await checkUpdate();
      setHasNewVersion(res.shouldUpdate);
      if (res.shouldUpdate && showDialog) {
        await check_update();
      }
    } catch (e) {
      message.warn("没有新版本");
    }
  };

  useEffect(() => {
    setTimeout(() => {
      checkNewVersion(false);
    }, 2000);
  }, []);

  useEffect(() => {
    const unlisten = listen<number>("updateProgress", ev => {
      if (ev.payload >= 0) {
        setUpdateProgress(ev.payload);
      } else {
        message.error("更新出错");
        setUpdateProgress(0);
      }
    })
    return () => {
      unlisten.then(f => f());
    }
  }, []);

  useEffect(() => {
    if (appStore.vendorCfg != null) {
      appWindow.setTitle(appStore.vendorCfg.layout.app_name);
      appWindow.setDecorations(!appStore.vendorCfg.layout.hide_sys_bar);
    }
  }, [appStore.vendorCfg]);

  useEffect(() => {
    const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
      const notice = ev.payload;
      if (notice.ClientNotice?.CheckUpdateNotice !== undefined) {
        checkNewVersion(true);
      }
    });
    return () => {
      unListenFn.then((unListen) => unListen());
    };
  }, []);

  return (
    <div>
      <div style={{ height: "4px", backgroundColor: location.pathname.startsWith("/app") ? "#f6f6f8" : "white", borderTop: "1px solid #e8e9ee" }} />
      <Header className={style.layout_header} {...props}
        style={{ backgroundColor: "white", boxShadow: "none", cursor: "move" }}
        data-tauri-drag-region
      >

        <Space style={{ marginLeft: "4px" }}>
          {location.pathname.startsWith(ADMIN_PATH) == false && (
            <>
              {appStore.vendorCfg?.layout.show_layout_switch == true && (
                <div>
                  <Segmented options={[
                    {
                      label: "展开",
                      value: "normal",
                      icon: <MenuFoldOutlined />,
                      title: "展开左侧主菜单"
                    },
                    {
                      label: "收起",
                      value: "simple",
                      icon: <MenuUnfoldOutlined />,
                      title: "收起左侧主菜单"
                    }
                  ]} size='large' value={appStore.simpleLayout ? "simple" : "normal"}
                    onChange={value => {
                      if (value == "simple") {
                        appStore.simpleLayout = true;
                      } else if (value == "normal") {
                        appStore.simpleLayout = false;
                      }
                    }} />
                </div>
              )}
              <QuickAccess />
              {appStore.simpleLayout == true && <AppNavigator />}
            </>
          )}
        </Space>

        {/* <div className={style.l} /> */}
        <div className={style.r}>
          {hasNewVersion == true && (
            <Button type="link" style={{ marginRight: "20px" }} onClick={e => {
              e.stopPropagation();
              e.preventDefault();
              check_update();
            }} disabled={updateProgress > 0}>
              <Space size="small">
                {updateProgress == 0 && (
                  <>
                    <InfoCircleOutlined />
                    <span>有新版本</span>
                  </>
                )}
                {updateProgress > 0 && (
                  <Progress type="line" percent={Math.ceil(updateProgress * 100)} showInfo={false} style={{ width: 50, paddingBottom: "16px" }} />
                )}
              </Space>
            </Button>
          )}



          {location.pathname.startsWith("/app/") && userStore.sessionId == "" && <ServerConnInfo />}

          {userStore.sessionId != "" && (
            <Space style={{ marginRight: "20px" }}>
              <UserPhoto logoUri={userStore.userInfo.logoUri} style={{ width: "20px", borderRadius: "10px", marginBottom: "4px", cursor: "default" }} />
              <span style={{ fontSize: "16px", fontWeight: 700, cursor: "default" }}>{userStore.userInfo.displayName}</span>
              <Button type="text" style={{ minWidth: 0, padding: "0px 0px", color: "grey" }} title='退出登录'
                onClick={e => {
                  e.stopPropagation();
                  e.preventDefault();
                  if (appStore.inEdit) {
                    message.info("请先保存修改内容");
                    return;
                  }
                  userStore.showLogout = true;
                  userStore.accountsModal = false;
                }}>
                <LogoutOutlined style={{ fontSize: "16px" }} />
              </Button>
            </Space>
          )}

          {appStore.vendorCfg?.layout.feedback_url != "" && (
            <Button type="text" icon={<MehFilled style={{ fontSize: "20px", color: "grey" }} />} title='反馈意见'
              style={{ marginRight: "10px" }}
              onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                if (appStore.vendorCfg?.layout.show_feedback_modal == true) {
                  appStore.showFeedBack = true;
                } else {
                  shell_open(appStore.vendorCfg?.layout.feedback_url ?? "");
                }
              }} />
          )}


          <Button type="text" icon={<EyeInvisibleFilled style={{ fontSize: "20px", color: "grey" }} />}
            title='隐藏窗口' onClick={e => {
              e.stopPropagation();
              e.preventDefault();
              handleClick('hide');
            }} />
          {appStore.vendorCfg?.layout.hide_sys_bar == true && (
            <>
              <div className={style.btnMinimize} onClick={() => handleClick('minimize')} title="最小化" />
              <div className={style.btnMaximize} onClick={() => handleClick('maximize')} title="最大化/恢复" />
              <div className={style.btnClose} onClick={() => handleClick('exit')} title="关闭应用" />
            </>
          )}
        </div>
      </Header >
      {appStore.showFeedBack == true && (
        <FeedBackModal onClose={() => appStore.showFeedBack = false} />
      )}
    </div >
  );
};

export default observer(MyHeader);
